package com.sunc.demo.order.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.sunc.demo.item.entity.Item;
import com.sunc.demo.order.feign.ItemFeignClient;
import com.sunc.demo.order.util.OrderProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class LocalItemService {

    //Spring框架对RESTful方式的http请求做了封装，来简化操作
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ItemFeignClient itemFeignClient;

    @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")//进行容错处理
    public Item queryItemById(Long id){
        return itemFeignClient.queryByItemId(id);
    }


//    @HystrixCommand(fallbackMethod = "queryItemByIdFallbackMethod")//进行容错处理
//    public Item queryItemById(Long id){
//
//        String serverId = "springcloud-demo-item";
//
//
//        String url = "http://"+ serverId+"/item/"+id;
//
//        return restTemplate.getForObject(url,Item.class);
//    }


    public Item queryItemByIdFallbackMethod(Long id){//请求失败执行的方法
        return new Item(id,"商品模块异常",null,null,null);
    }

//    public Item queryItemById(Long id){
//
//        String serverId = "springcloud-demo-item";
//
//        List<ServiceInstance> instances = discoveryClient.getInstances(serverId);
//
//        if (CollectionUtils.isEmpty(instances)){
//            return null;
//        }
//
//        ServiceInstance serviceInstance = instances.get(0);
//
//        String url = "http://"+ serviceInstance.getHost()+":"+serviceInstance.getPort()+"/item/"+id;
//
//        return restTemplate.getForObject(url,Item.class);
//    }


    //    @Value("${springclouddemo.item.url}")
//    private String itemUrl;
//    @Autowired
//    private OrderProperties orderProperties;

//    public Item queryItemById(Long id) {
//
//
////        String url = "http://127.0.0.1:8081/item/"+id;
////        String url = itemUrl+id;
//        String url = orderProperties.getItem().getUrl()+id;
//
//        return restTemplate.getForObject(url,Item.class);
//
//    }
}
